<?php

namespace app\admin\service\auth;

use app\admin\model\Role;
use think\facade\Db;
use app\admin\service\BaseService;

class RoleService extends BaseService
{

    /**
     * 获取列表
     * @param $data
     * @return mixed
     */
    public function getList($param)
    {
        $model = new Role();
        $searchFields = ['name','code'];//模糊搜索
        $search = ['status'];//精确搜索
        $fields = [];//查询字段
        $list = $this->paginateWithSearch($model, $param, $fields, $searchFields, $search ,'created_at','asc');
        foreach ($list['data'] as &$item) {
            $roleMenus = Db::name('role_menu')->where('role_id', $item['id'])->column('menu_id');
            $item['rules'] = implode(',', $roleMenus);
        }
        return success($list);
    }
    /**
     * 添加
     * @param $data
     * @return mixed
     */
    public function Add($data)
    {
      $model = new Role();
      $Unique = ['name','code'];
      $empty = ['code','name'];
      $check = $this->checkParams($model, $data, $Unique, $empty);
      if ($check !== true) {
          return fail($check['msg']);
      }
      Db::startTrans();
        try{
            $data['created_at'] = time();
            $model->insert($data);
            Db::commit();
            // writes('添加', 1);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    /**
     * 编辑
     * @param $id
     * @param $data
     * @return mixed
     */
    public function Edit($id, $data)
    {
      $model = new Role();
      $res = $model->where('id', $id)->find();
      if (empty($res)) {
        return fail('角色不存在');
      }
      $Unique = ['name','code'];
      $empty = ['code','name'];
      $data['id'] = $id;
      $check = $this->checkParams($model, $data, $Unique, $empty);
      if ($check !== true) {
          return fail($check['msg']);
      }
      $rules = $data['rules'] ?? null;
      unset($data['rules']);
      Db::startTrans();
        try{
            $data['updated_at'] = time();
            $model->where('id', $id)->update($data);
            if ($rules !== null) {
                Db::name('role_menu')->where('role_id', $id)->delete();
                $menuIds = array_filter(explode(',', $rules));
                $insertData = [];
                foreach ($menuIds as $menuId) {
                    $insertData[] = [
                        'role_id' => $id,
                        'menu_id' => intval($menuId)
                    ];
                }
                if (!empty($insertData)) {
                    Db::name('role_menu')->insertAll($insertData);
                }
            }
            Db::commit();
            // writes('编辑', 1);
            return success();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('操作失败:' . $e->getMessage());
        }
    }
    /**
     * 删除
     * @param $ids
     * @return mixed
     */
    public function Delete($ids)
    {
      $model = new Role();
      $ids = array_filter(array_unique($ids));
      if (empty($ids)) {
          return fail('请选择要删除的数据');
      }
      foreach ($ids as $id) {
          if (!is_numeric($id) || $id <= 0) {
              return fail('包含错误ID值'.$id);
          }
      }
      if (in_array(1, $ids)) {
          return fail('不可删除ID：1');
      }
      $ids = array_map('intval', $ids);

      try {
        Db::name('role_menu')->whereIn('role_id', $ids)->delete();
        Db::name('admin_role')->whereIn('role_id', $ids)->delete();
        $res = $model->whereIn('id', $ids)->delete();
          $res = $model->whereIn('id', $ids)->delete();
          if ($res === false) {
            Db::rollback();
            return fail('删除失败');
          }
          // writes('删除日志: ' . implode(',', $ids), 3);
          return success();
      } catch (\Exception $e) {
          return fail('系统错误'.$e->getMessage());
      }
    }
}
